package com.bkhc.product.service;

import com.bkhc.common.entity.User;
import com.bkhc.common.enu.BrandStatusEnum;
import com.bkhc.common.enu.PartnershipEnum;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.repository.UmcRepository;
import com.bkhc.common.service.UserService;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.OrderItemVo;
import com.bkhc.common.vo.OrderVo;
import com.bkhc.common.vo.UserBean;
import com.bkhc.product.entity.Brand;
import com.bkhc.product.entity.Employee;
import com.bkhc.product.entity.Partner;
import com.bkhc.product.entity.PartnerBrand;
import com.bkhc.product.repository.*;
import com.bkhc.product.vo.EmployeeVo;
import com.bkhc.product.vo.PartnerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class PartnerService {

    @Autowired
    private PartnerRepository repository;

    @Autowired
    private UserService userService;

    @Autowired
    private UmcRepository mcRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private EmployeeRepository employeeRepository;
    @Autowired
    private PartnerRepository partnerRepository;
    @PersistenceContext
    private EntityManager entityManager;


    @Autowired
    private PartnerAppRepository partnerAppRepository;

    @Autowired
    private PartnerBrandRepository partnerBrandRepository;


    public ResultJson<?> addPartner(Partner partner) {
        String partnerName = partner.getPartnerName();
        Partner partnerTem = repository.findByPartnerName(partnerName);
        if (partnerTem != null) {
            return ResultJson.failure(ResultCode.ISEXIT_RESURCE);
        }
//        List<String> brandCodes = partner.getBrandCodes();
//        if (CollectionUtils.isEmpty(brandCodes)) {
//            return ResultJson.failure(ResultCode.BAD_REQUEST);
//        }
        String manager = partner.getManager();
//        if (StringUtils.isEmpty(manager)) {
//            return ResultJson.failure(ResultCode.NO_PARTNER_EMP);
//        }
        Employee emp = new Employee();
        User user = new User();
        user.setPhone(partner.getMobile());
        user.setUsername(partner.getUsername());
        user.setFullName(partner.getFullName());
        User userEntity = mcRepository.sysUserToUmc(user);
        UserBean crruentUser = CommonUtil.getCrruentUser();
        emp.setUserId(userEntity.getUserId());
        emp.setMail(userEntity.getEmail());
        emp.setMobile(userEntity.getPhone());
        emp.setUsername(userEntity.getUsername());
        emp.setAdminFlag("Y");
        emp.setCreator(crruentUser.getUserId());
        emp.setUpdator(crruentUser.getUserId());
        partner.setManager(userEntity.getUserId());
        partner.setCreator(crruentUser.getUserId());
        partner.setUpdator(crruentUser.getUserId());
        repository.save(partner);
        emp.setPartnerCode(partner.getPartnerCode());
        employeeRepository.save(emp);
        partner.setEmployee(emp);
        pushPartnerApp(partner);
        return ResultJson.success();
    }

    private void pushPartnerApp(Partner partner) {
        Employee emp = partner.getEmployee();
        EmployeeVo evo = new EmployeeVo();
        evo.setCreator(emp.getCreator());
        evo.setPartnerCode(emp.getPartnerCode());
        evo.setAdminFlag(emp.getAdminFlag());
        evo.setMail(emp.getMail());
        evo.setMobile(emp.getMobile());
        evo.setUpdator(emp.getUpdator());
        evo.setUsername(emp.getUsername());
        evo.setCreator(emp.getCreator());
        evo.setUserId(emp.getUserId());
        PartnerVo pvo = new PartnerVo();
        pvo.setCreateDate(partner.getCreateDate());
        pvo.setPartnerName(partner.getPartnerName());
        pvo.setPartnerCode(partner.getPartnerCode());
        pvo.setCreator(partner.getCreator());
        pvo.setPartnership(partner.getPartnership());
        pvo.setEmployee(evo);
        pvo.setProfile(partner.getProfile());
        pvo.setWebsit(partner.getWebsit());
        pvo.setPartnerLog(partner.getPartnerLog());
        pvo.setBusinessLicense(partner.getBusinessLicense());
        pvo.setProfile(partner.getProfile());
        pvo.setUpdator(partner.getUpdator());
        pvo.setCreator(partner.getCreator());
        partnerAppRepository.addPartner(pvo);
    }

    public ResultJson<?> queryPartnerList(String partnerName, String brandCode, int pageIndex, int pageSize) {
        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex - 1, pageSize, Sort.by(orders));
        PageUtil pageUtil = new PageUtil();
        if (StringUtils.isEmpty(brandCode) && StringUtils.isEmpty(partnerName)) {

            Page<Partner> page = repository.findAll(pageRequest);
            pageUtil = new PageUtil(page);
            ResultJson<PageUtil> resultJson = ResultJson.success();
            resultJson.setData(pageUtil);
            return resultJson;
        }
        if (StringUtils.isEmpty(brandCode) && !StringUtils.isEmpty(partnerName)) {
            Partner p = new Partner();
            p.setPartnerName(partnerName);
            Page<Partner> page = repository.findAll(p, pageRequest);
            pageUtil = new PageUtil(page);
            ResultJson<PageUtil> resultJson = ResultJson.success();
            resultJson.setData(pageUtil);
            return resultJson;
        }
        if (!StringUtils.isEmpty(brandCode)) {
            PartnerBrand partnerBrand = partnerBrandRepository.findByBrandCode(brandCode);
            if(partnerBrand==null){
                pageUtil = new PageUtil();
                pageUtil.setTotal(0);
                ResultJson<PageUtil> resultJson = ResultJson.success();
                resultJson.setData(pageUtil);
                return resultJson;
            }
            Partner partner = repository.findByPartnerCode(partnerBrand.getPartnerCode());
            pageUtil = new PageUtil();
            if (partner != null && (partner.getPartnerName().equals(partnerName)||partnerName==null)) {
                pageUtil.setTotal(1);
                List<Partner> partners = new ArrayList<>();
                partners.add(partner);
                pageUtil.setList(partners);
                ResultJson<PageUtil> resultJson = ResultJson.success();
                resultJson.setData(pageUtil);
                return resultJson;
            }


        }
        pageUtil = new PageUtil();
        pageUtil.setTotal(0);
        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(pageUtil);
        return resultJson;
    }

    public ResultJson<?> queryPartnerDetail(String partnerCode) {
        Partner p = repository.findByPartnerCode(partnerCode);
        if(p!=null){
           Employee e = employeeRepository.findByPartnerCode(partnerCode);
            p.setManager(e.getUserId());
            List<PartnerBrand> partnerBrandList=partnerBrandRepository.findByPartnerCode(partnerCode);
            p.setPartnerBrands(partnerBrandList);
        }
        ResultJson<Partner> resultJson = ResultJson.success();
        resultJson.setData(p);
        return resultJson;
    }

    public ResultJson<?> updatePartner(Partner partner) {
        Partner p = repository.findByPartnerCode(partner.getPartnerCode());
        p.setPartnership(partner.getPartnership());
        p.setWebsit(partner.getWebsit());
        p.setProfile(partner.getProfile());
        repository.save(p);
        employeeRepository.deleteByPartnerCode(p.getPartnerCode());
        Employee emp = new Employee();
        User u = mcRepository.findByUserId(partner.getManager());
        UserBean crruentUser = CommonUtil.getCrruentUser();
        emp.setUserId(partner.getManager());
        emp.setMail(u.getEmail());
        emp.setMobile(u.getPhone());
        emp.setUsername(u.getUsername());
        emp.setAdminFlag("Y");
        emp.setCreator(crruentUser.getUserId());
        emp.setUpdator(crruentUser.getUserId());
        emp.setPartnerCode(p.getPartnerCode());
        employeeRepository.save(emp);
        List<PartnerBrand> partnerBrands = partnerBrandRepository.findByPartnerCode(partner.getPartnerCode());
        p.setEmployee(emp);
        p.setPartnerBrands(partnerBrands);
        pushPartnerApp(p);
       return ResultJson.success();
    }

    public ResultJson<?> generatePartnerAcount() {
        Query accountNumber = entityManager.createNativeQuery("SELECT NEXTVAL('partnerSeq');");
        Object max = accountNumber.getSingleResult();
        //Integer max = memberrepository.generateBusinessAcount();
        String nextNum = (Integer)max+"";
        String 	prefix = "PT";
        StringBuffer prefixBuf = new StringBuffer(prefix);
        //工号总长度8位
        int length = 8;
        int tem  = (prefix+nextNum).length();
        int  needzero = length -tem;
        for(int i=0;i<needzero;i++){
            prefixBuf.append("0");
        }
        prefixBuf.append(nextNum);
        ResultJson result = ResultJson.success();
        result.setData(prefixBuf);
        return result;
    }

    public ResultJson<?> deletePartner(String partnerCode) {
        UserBean userBean = CommonUtil.getCrruentUser();
        UserPermission userPermission = userService.queryUserPermission(userBean.getUserId());
        boolean isAdmin = userPermission.getRoles().stream().anyMatch(roleDetail -> "admin".equals(roleDetail.getRole_code()));
        if(isAdmin){
            partnerBrandRepository.deleteByPartnerCode(partnerCode);
            employeeRepository.deleteByPartnerCode(partnerCode);
            partnerRepository.deleteByPartnerCode(partnerCode);
            partnerAppRepository.deletePartnerCode(partnerCode);
        }
        return ResultJson.success();
    }
}
